package com.qixiaobao.nondirect.invoice.service.impl;

import com.qixiaobao.common.exception.UtilException;
import com.qixiaobao.common.utils.StringUtils;
import com.qixiaobao.insure.domain.MatchInsure;
import com.qixiaobao.insure.mapper.MatchInsureMapper;
import com.qixiaobao.nondirect.invoice.domain.dto.NonDirectInvoiceDTO;
import com.qixiaobao.nondirect.invoice.domain.vo.NonDirectWaitInvoiceChargeVO;
import com.qixiaobao.nondirect.invoice.domain.vo.NonDirectWaitInvoiceVO;
import com.qixiaobao.nondirect.invoice.mapper.InvoiceFileMapper;
import com.qixiaobao.nondirect.invoice.mapper.NonDirectWaitInvoiceMapper;
import com.qixiaobao.nondirect.invoice.service.INonDirectWaitInvoiceService;
import com.qixiaobao.system.domain.Dict;
import com.qixiaobao.nondirect.invoice.domain.domain.InvoiceFile;
import com.qixiaobao.system.domain.SignCompany;
import com.qixiaobao.system.domain.dto.ChargeDTO;
import com.qixiaobao.system.mapper.DictMapper;
import com.qixiaobao.system.mapper.SignCompanyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Description 非直投发票管理 - 待开票 业务层处理
 * @Author yangxm
 * @Date 2025/7/4 13:49
 */
@Slf4j
@Service
public class NonDirectWaitInvoiceServiceImpl implements INonDirectWaitInvoiceService {

    @Autowired
    private NonDirectWaitInvoiceMapper nonDirectWaitInvoiceMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private SignCompanyMapper signCompanyMapper;
    @Autowired
    private InvoiceFileMapper invoiceFileMapper;
    @Autowired
    private MatchInsureMapper matchInsureMapper;

    /**
     * 查询待开票列表
     * @param nonDirectInvoiceDTO
     * @return
     */
    @Override
    public List<NonDirectWaitInvoiceVO> selectWaitInvoiceList(NonDirectInvoiceDTO nonDirectInvoiceDTO) {
        long begin = System.currentTimeMillis();
        log.info("查询非直投发票管理 - 待开票列表, 参数：{}", nonDirectInvoiceDTO);
        List<NonDirectWaitInvoiceVO> list = nonDirectWaitInvoiceMapper.selectWaitInvoiceList(nonDirectInvoiceDTO);
        if (StringUtils.isNotEmpty(list)){
            //字典
            Map<String, String> invoiceTypeMap = dictMapper.selectDictListByType("invoicetype").stream().
                    collect(Collectors.toMap(Dict::getK, Dict::getVal));

            NonDirectWaitInvoiceVO item;
            for (int i = 0; i < list.size(); i++) {
                item = list.get(i);
                item.setIndex(i + 1);
                item.setInvoiceTypeVal(invoiceTypeMap.get(item.getInvoiceType()));
            }
        }
        log.info("查询非直投发票管理 - 待开票列表, 总耗时：{}ms", System.currentTimeMillis() - begin);
        return list;
    }

    /**
     * @Description 待开票 - 金额统计
     * @Author yangxm
     * @Date 2025/7/4 14:43
     * @param nonDirectInvoiceDTO
     * @return java.math.BigDecimal
     */
    @Override
    public BigDecimal selectWaitInvoiceTotal(NonDirectInvoiceDTO nonDirectInvoiceDTO) {
        return nonDirectWaitInvoiceMapper.selectWaitInvoiceTotal(nonDirectInvoiceDTO);
    }

    /**
     * @Description 待开票 - 费用详情
     * @Author yangxm
     * @Date 2025/7/4 15:12
     * @param chargeDTO
     * @return java.util.List<com.qixiaobao.nondirect.invoice.domain.vo.NonDirectWaitInvoiceCharge>
     */
    @Override
    public List<NonDirectWaitInvoiceChargeVO> selectInsureFeeChargeList(ChargeDTO chargeDTO) {
        long begin = System.currentTimeMillis();
        log.info("查询非直投发票管理 - 待开票 - 费用详情, 参数：{}", chargeDTO);
        if (chargeDTO.getInsureFeeId() == null){
            throw new UtilException("参数错误");
        }
        List<NonDirectWaitInvoiceChargeVO> list = nonDirectWaitInvoiceMapper.selectInsureFeeChargeList(chargeDTO);
        log.info("查询非直投发票管理 - 待开票 - 费用详情sql, 耗时：{}ms", System.currentTimeMillis() - begin);
        if (StringUtils.isNotEmpty(list)){

            //获取所有的保单id
            List<Long> insureIdList = list.stream().map(NonDirectWaitInvoiceChargeVO::getInsureId).distinct().collect(Collectors.toList());
            //根据保单id，查询匹配后供应商简称
            List<MatchInsure> matchInsureList = matchInsureMapper.selectToSupplyShortNameList(insureIdList);
            Map<Long,String> toSupplyShortNameMap = null;
            if (StringUtils.isNotEmpty(matchInsureList)){
                toSupplyShortNameMap = matchInsureList.stream().collect(Collectors.toMap(MatchInsure::getFromInsureId, MatchInsure::getToSupplyShortName));
            }

            // 字典
            List<Dict> dictList = dictMapper.selectDictList();
            Map<String, Map<String, String>> dictMap = new ConcurrentHashMap<>();
            if (StringUtils.isNotEmpty(dictList)) {
                dictMap = dictList.stream()
                        .filter(c -> c.getVal() != null)
                        .collect(Collectors.groupingBy(Dict::getType, Collectors.toMap(Dict::getK, Dict::getVal)));
            }
            Map<String, String> insurePeriodMap = dictMap.get("insureperiod");
            Map<String, String> mealnameMap = dictMap.get("mealname");
            Map<String, String> maimRatioMap = dictMap.get("maimRatio");
            Map<String, String> jobtypeMap = dictMap.get("jobtype");

            //付款单位
            Map<Long, String> payCompanyNameMap = signCompanyMapper.selectSignCompanyNameList().stream()
                    .collect(Collectors.toMap(SignCompany::getId, SignCompany::getCompanyName));

            // 发票文件
            Map<Long, InvoiceFile> invoiceFileMap = null;
            //根据保费id查询发票信息
            List<InvoiceFile> invoiceFileList = invoiceFileMapper.selectInvoiceFileByInsureFeeId(chargeDTO.getInsureFeeId());
            if (StringUtils.isNotEmpty(invoiceFileList)){
                invoiceFileMap = invoiceFileList.stream().collect(Collectors.toMap(InvoiceFile::getInsureFeeId, e -> e));
            }

            NonDirectWaitInvoiceChargeVO item;
            InvoiceFile invoiceFile;

            for (int i = 0; i < list.size(); i++) {
                item = list.get(i);
                item.setIndex(i + 1);
                item.setMealNameVal(mealnameMap.get(item.getMealName()));
                item.setMaimRatioVal(maimRatioMap.get(item.getMaimRatio()));
                item.setJobTypeVal(jobtypeMap.get(item.getJobType()));
                item.setInsurePeriodVal(insurePeriodMap.get(item.getInsurePeriod()));
                item.setInsurePerson("增员:" + item.getAddNum() + ";减员:" + item.getMinusNum());
                item.setAbandonFlagVal(item.getAbandonFlag() == 1 ? "是" : "否");
                item.setFinanceReckonVal(StringUtils.equals("0", item.getFinanceReckon()) ? "否" : "是");
                item.setPayCompanyName(payCompanyNameMap.get(item.getPayCompanyId()));
                item.setActualPayCompanyName(payCompanyNameMap.get(item.getActualPayCompanyId()));
                if (StringUtils.isNotEmpty(invoiceFileMap)){
                    invoiceFile = invoiceFileMap.get(item.getInsureFeeId());
                    if (invoiceFile != null){
                        item.setInvoiceNums(invoiceFile.getInvoiceNums());
                        item.setInvoiceDates(invoiceFile.getInvoiceDates());
                        item.setInvoiceMoneys(invoiceFile.getInvoiceMoneys());
                    }
                }
                if (StringUtils.isNotEmpty(toSupplyShortNameMap)){
                    item.setToSupplyShortName(toSupplyShortNameMap.getOrDefault(item.getInsureId(), ""));
                }
            }
        }
        log.info("查询非直投发票管理 - 待开票 - 费用详情, 总耗时：{}ms", System.currentTimeMillis() - begin);
        return list;
    }
}
